import requests
import time

from email.mime.text import MIMEText
from email.header import Header
from smtplib import SMTP_SSL

def mailCall(mail_content):
    host_server = 'smtp.qq.com'
    sender_qq = '111111111'
    pwd = 'asdqweasfasqweqw'
    sender_qq_mail = '111111111@qq.com'
    receiver = '222222222@qq.com'
    #mail_content = '你好，现在在进行一项用python登录qq邮箱发邮件的测试'
    mail_title = '💴购买提醒'

    smtp = SMTP_SSL(host_server)
    smtp.set_debuglevel(0)
    smtp.ehlo(host_server)
    smtp.login(sender_qq, pwd)

    msg = MIMEText(mail_content, "plain", 'utf-8')
    msg["Subject"] = Header(mail_title, 'utf-8')
    msg["From"] = sender_qq_mail
    msg["To"] = receiver
    smtp.sendmail(sender_qq_mail, receiver, msg.as_string())
    smtp.quit()

def p2f(x):
    return -float(x.strip('%'))

ziti = '<font face="Courier New, Courier, monospace">名称 : {}\r\n  幅度 : {}   下手: {}</font>\r\n'

def GetData():
    urlbase = "https://www.dayfund.cn/ajs/ajaxdata.shtml?showtype=getfundvalue&fundcode={:06}&t=2100"
    
    namedic =  [
        {"name":"汇添富中证新能源汽车产业指数","Number":501058,"Base":1.5,"Toady":0,"Buy":False},
        {"name":"兴全合润混合","Number":163406,"Base":1,"Toady":0,"Buy":False},
        {"name":"易方达新收益混合C","Number":1217,"Base":1,"Toady":0,"Buy":False},
        ]

    headers={"User-Agent" : "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.6) ",
    "Accept" : "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "Accept-Language" : "en-us",
    "Connection" : "keep-alive",
    "Accept-Charset" : "GB2312,utf-8;q=0.7,*;q=0.7"}

    try:
        for index in range(len(namedic)):
            iurl = urlbase.format(namedic[index]['Number'])
            r = requests.get(iurl,headers=headers,verify=False)
            reptext = r.text.split("|")
            namedic[index]["Toady"] = reptext[4]
            s = p2f(reptext[4])
            if s > namedic[index]["Base"]:
                namedic[index]["Buy"] = True
        return namedic
    except AttributeError:
        return None


def Scdule():
    print("Start!\n")
    while True:
        xiaoshi = time.strftime("%H", time.localtime())
        fzs = time.strftime("%M", time.localtime())
        if int(xiaoshi) == 14:
            if 25 < int(fzs) < 50:
                # 尝试10次获取 今日数据 失败邮件发送空
                for i in range(10):
                    data = GetData()
                    if data == None:
                        time.sleep(30)
                        continue
                    break
                # 格式化数据发送邮箱
                MailText = ""
                if data != None:
                    for kk in data:
                        MailText += ziti.format(kk['name'],kk['Toady'],kk['Buy'])
                # 发送邮件通知
                mailCall(MailText)
                # 演示避免多次发送邮件
                time.sleep(60*20)
            # 调整精度
            time.sleep(60*2)
        # 其他时间不运行代码
        print("\n[-]正在运行中\n现在时间:",time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
        time.sleep(60*10)
        

Scdule()